//app.js
var config = require("pages/config.js")
var utils = require("./utils/util.js")
var broadcast = require("./utils/broadcast.js")
App({
  globalData: {
    chargeStatus: null,
    userInfo: null,
    // 充电状态0表示充电中,1表示时间到自停,2表示充电结束，用户手动拔出，-2表示设备异常断电
    isRidingBike: null,
    system: {
      windowWidth: 0,
      windowHeight: 0
    }
  },
  onLaunch: function () {
    var that = this
    this.getSystemInfo()
    this.getUserInfo()
    //调用API从本地缓存中获取数据
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
    broadcast.on("login", function (data, event) {
      that.login()
    })
  },
  getSystemInfo: function () {
    wx.getSystemInfo({
      success: res => {
        this.globalData.system = {
          windowWidth: res.windowWidth,
          windowHeight: res.windowHeight
        }
      }
    })
  },
  onShow: function () {
    // this.getUserInfo();
    // wx.redirectTo({
    //   url: '/pages/index/index',
    // })
  },
  /**
   * 获取用户信息
   */
  getUserInfo: function (cb) {
    var that = this
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //获取用户信息
      var rememberMe = wx.getStorageSync('token')
      if (rememberMe != null && rememberMe != "") {
        wx.request({
          url: config.url_all + '/api/getUserinfo',
          header: {
            'Rememberme': rememberMe,
            'content-type': 'application/x-www-form-urlencoded'
          },
          method: 'POST',
          success: function (res) {
            var type = res.data.type
            var userInfo = that.globalData.userInfo
            if (type == 'SUCCESS') {
              userInfo = res.data.data
              that.setUserInfo(userInfo)
              that.bindPhone()
              // wx.showModal({
              //   title: 'hello',
              //   content: '登陆成功了',
              // })
            } else {
              that.login()
            }
          }
        })
      }

    }
  },
  // 用户登录
  login: function () {
    let that = this
    wx.login({
      success: function (res) {
        // 获取用户授权结果
        wx.getSetting({
          success: result => {
            if (result.authSetting["scope.userInfo"]) {
              wx.getUserInfo({
                success: res1 => {
                  that.loginWithCode(res.code, res1)
                }
              })
            } else {
              if (wx.openSetting) {
                wx.openSetting({
                  success: function (res) {
                    //尝试再次登录
                    that.login()
                  }
                })
              } else {
                wx.showModal({
                  title: '授权提示',
                  content: '小程序需要您的微信授权才能使用哦~ 错过授权页面的处理方法：删除小程序->重新搜索进入->点击授权按钮'
                })
              }
            }
          }
        })
      }
    })
  },
  loginWithCode: function (code, res1) {
    wx.showLoading({
      title: '登录中...',
    })
    var that = this
    //发起登录请求
    wx.request({
      url: config.url_all + '/loginWithWxCode',
      data: {
        code: code
      },
      success: function (res) {
        if (res.data.type === 'SUCCESS') {
          wx.hideLoading()
          //将token保存到程序内
          var token = res.header.Rememberme
          wx.setStorageSync('token', token)
          var userInfo = res.data.data
          // 如果没有用户信息，获取用户微信信息上传至服务器
          // if (userInfo.username == null || userInfo.username === '') {
          wx.request({
            url: config.url_all + '/wechat/user/updateUserinfo',
            header: {
              Rememberme: token
            },
            data: {
              rawData: res1.rawData,
              signature: res1.signature,
              encryptedData: res1.encryptedData,
              iv: res1.iv
            },
            success: res2 => {
              if (res2.data.type === 'SUCCESS') {
                userInfo = res2.data.data
                that.setUserInfo(userInfo)
                that.bindPhone()
              }
            }
          })
          // } else {
          // that.setUserInfo(userInfo)
          // that.bindPhone()
          // }
        } else {
          wx.hideLoading()
          broadcast.fire("login-error")
          wx.showModal({
            title: '提示',
            content: '登录失败',
            cancelText: '取消',
            confirmText: '重新登录',
            success: (res) => {
              if (res.confirm) {
                that.login()
              }
            }
          })
        }
      },
      fail: function () {
        wx.hideLoading()
        broadcast.fire("login-error")
        wx.showToast({
          title: '登录失败',
        })
      }
    })
  },
  /**
 * 存储用户信息
 */
  setUserInfo: function (userInfo) {
    var that = this
    var token = wx.getStorageSync('token')
    wx.getUserInfo({
      success: res => {
        wx.request({
          url: config.url_all + '/wechat/user/updateUserinfo',
          header: {
            Rememberme: token
          },
          data: {
            rawData: res.rawData,
            signature: res.signature,
            encryptedData: res.encryptedData,
            iv: res.iv
          },
          success: res2 => {
            if (res2.data.type === 'SUCCESS') {
              userInfo = res2.data.data
              console.log('更新后的用户信息' + userInfo)
              this.globalData.userInfo = userInfo
              broadcast.fire("login-success", userInfo)
            }
          }
        })
      }
    })
  },
  /**
   * 绑定手机号码提示
   */
  bindPhone: function () {
    // if (this.globalData.userInfo.phone == null || this.globalData.userInfo.phone === '') {
    //   wx.showModal({
    //     title: '提示',
    //     content: '为了更好的为您服务，请先绑定手机号码',
    //     showCancel: false,
    //     confirmText: '确定',
    //     success: (res) => {
    //       if (res.confirm) {
    //         wx.navigateTo({
    //           url: './pages/Register/Register'
    //         });
    //       }
    //     }
    //   })
    //   return false
    // }
    // return true
  }
})
